import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/config/route/common_widget_route.dart';
import 'package:dk_flutter_module_sale/sale/api/sale_in_map_tool_api.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/map_tool/bean/bean_house_source_list.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/map_tool/page/page_goal_house_source_list.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/map_tool/widget/widget_house_source_item.dart';
import 'package:flutter/cupertino.dart';

class PageHouseSourceHome extends CommonPage {
  final EventBus searchEventBus;
  final int index;
  final String searchContent;
  PageHouseSourceHome(this.searchEventBus, this.index, this.searchContent)
      : super();
  @override
  void onInitState(CommonPageBloc pageBloc, {Map<String, Bloc> extraBlocMap}) {
    loadCommunityNameSearch(pageBloc, searchContent);
  }

  void loadHouseSourceList(
      CommonPageBloc pageBloc, CommunitySearchBean communitySearchBean) {
    Map<String, dynamic> paramsMap = {};
    paramsMap["index"] = 1;
    paramsMap["size"] = 20;
    paramsMap["taskStatus"] = index;
    if (communitySearchBean != null) {
      paramsMap["communityId"] = communitySearchBean.xiaoquId;
    }
    pageBloc.dataHttpGet(
      path: SaleInMapToolApi.houseSourceList,
      queryMap: paramsMap,
      handleResult: (dynamic data) {
        HouseSourceListBean houseSourceListBean =
            HouseSourceListBean.fromJson(data);
        pageBloc.switchPage(HouseSourceHomeWidget(
            pageBloc, index, searchEventBus, houseSourceListBean,searchContent,communitySearchBean));
      },
      showLoading: false,
      showFailMsg: false,
      showSuccessMsg: false,
    );
  }

  Future<void> loadCommunityNameSearch(
      CommonPageBloc pageBloc, String communityName) async {
    if (communityName.length > 0) {
      Map<String, dynamic> paramsMap = {};
      paramsMap["name"] = communityName;
      pageBloc.dataHttpGet(
        path: SaleInMapToolApi.houseSourceSearchList,
        queryMap: paramsMap,
        handleResult: (dynamic result) {
          List<CommunitySearchBean> datas;
          CommunitySearchBean communitySearchBean;
          datas = (result as List) != null
              ? (result as List)
                  .map((i) => CommunitySearchBean.fromJson(i))
                  .toList()
              : null;
          if (listNotEmpty(datas)) {
            communitySearchBean = datas[0];
          } else {
            communitySearchBean = null;
          }
          loadHouseSourceList(pageBloc, communitySearchBean);
        },
        showLoading: false,
        showSuccessMsg: false,
        showFailMsg: false,
      );
    } else {
      loadHouseSourceList(pageBloc, null);
    }
  }
}

// ignore: must_be_immutable
class HouseSourceHomeWidget extends StatefulWidget {
  final CommonPageBloc pageBloc;
  final HouseSourceListBean houseSourceListBean;
  final CommunitySearchBean communitySearchBean;

  EventBus searchEventBus;
  String searchContent;
  int index;
  HouseSourceHomeWidget(
      this.pageBloc, this.index, this.searchEventBus, this.houseSourceListBean,this.searchContent,this.communitySearchBean);
  @override
  HouseSourceHomeState createState() {
    return HouseSourceHomeState(this.pageBloc, houseSourceListBean,this.searchContent,this.communitySearchBean);
  }
}

class HouseSourceHomeState extends State<HouseSourceHomeWidget>
    with SingleTickerProviderStateMixin {
  CommonPageBloc pageBloc;
  DkEasyRefreshController easyRefreshController;
  //搜索关键字
  String searchContent;
  int pageIndex = 1;
  final int pageSize = 20;
  //房源
  HouseSourceListBean houseSourceListBean;
  //请求参数
  Map<String, dynamic> paramsMap = {};
  //搜索结果
  CommunitySearchBean communitySearchBean;
  HouseSourceHomeState(this.pageBloc, this.houseSourceListBean,this.searchContent,this.communitySearchBean) {
    easyRefreshController = DkEasyRefreshController();
  }

  @override
  void initState() {
    super.initState();
    paramsMap["size"] = pageSize;
    paramsMap["taskStatus"] = widget.index;
    widget.searchEventBus
        ?.on<TabChangeContentEvent>()
        ?.listen((TabChangeContentEvent event) {
      setState(() {
        searchContent = event.searchContent;
      });
      loadCommunityNameSearch(searchContent);
    });
  }

  @override
  Widget build(BuildContext context) {
    bool noMore = houseSourceListBean.houseTask.length >=
        this.houseSourceListBean.totalCount;
    return Container(
      child: DkRefreshListWidget.custom(
          controller: easyRefreshController,
          onRefresh: refreshList,
          onLoad: noMore ? null : loadMore,
          emptyWidget: houseSourceListBean.houseTask.length == 0
              ? LogicPage.emptyPage(emptyParam: SaleConfig.emptyPageParam)
              : null,
          slivers: <Widget>[
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  HouseSourceBean item = houseSourceListBean.houseTask[index];
                  return WidgetHouseSourceItem(
                    hasHead: index > 0 ? true : false,
                    houseSourceBean: item,
                    houseSourceItemCallback: () {
                      RouteUtil.goPage(
                          CommonWidgetRoute
                              .COMMON_HOUSE_SOURCE_FOLLOWING_DETAIN,
                          widgetContext: context,
                          params: {"id": item.id.toString()});
                    },
                  );
                },
                childCount: houseSourceListBean.houseTask.length,
              ),
            ),
          ]),
    );
  }

  Future<void> loadMore() async {
    paramsMap['index'] = (++this.pageIndex);
    if (communitySearchBean != null) {
      paramsMap["communityId"] = communitySearchBean.xiaoquId;
    }
    pageBloc.dataHttpGet(
        path: SaleInMapToolApi.houseSourceList,
        queryMap: paramsMap,
        handleResult: (dynamic data) {
          setState(() {
            HouseSourceListBean result = HouseSourceListBean.fromJson(data);
            houseSourceListBean.houseTask.addAll(result.houseTask);
            easyRefreshController.finishLoad(
                success: true,
                noMore:
                    houseSourceListBean.houseTask.length >= result.totalCount);
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishLoad(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishLoad(success: false);
        });
  }

  Future<void> refreshList({showLoading = false}) {
    pageIndex = 1;
    paramsMap['index'] = pageIndex;
    if (communitySearchBean != null) {
      paramsMap["communityId"] = communitySearchBean.xiaoquId;
    } else {
      paramsMap.remove("communityId");
    }
    pageBloc.dataHttpGet(
      path: SaleInMapToolApi.houseSourceList,
      queryMap: paramsMap,
      handleResult: (dynamic data) {
        setState(() {
          houseSourceListBean = HouseSourceListBean.fromJson(data);
          easyRefreshController.finishRefresh(success: true);
        });
      },
      showLoading: showLoading,
      handleErrorCode: (responseData) {
        setState(() {
          showShortToast(responseData.msg);
          easyRefreshController.finishRefresh(success: false);
        });
      },
      handleFailResult: (dynamic data1, dynamic data2) {
        easyRefreshController.finishRefresh(success: false);
      },
    );
    return new Future.value();
  }

  Future<void> loadCommunityNameSearch(String communityName) async {
    if (communityName.length > 0) {
      Map<String, dynamic> paramsMap = {};
      paramsMap["name"] = communityName;
      pageBloc.dataHttpGet(
        path: SaleInMapToolApi.houseSourceSearchList,
        queryMap: paramsMap,
        handleResult: (dynamic result) {
          List<CommunitySearchBean> datas;
          datas = (result as List) != null
              ? (result as List)
                  .map((i) => CommunitySearchBean.fromJson(i))
                  .toList()
              : null;
          if (listNotEmpty(datas)) {
            communitySearchBean = datas[0];
          } else {
            communitySearchBean = null;
          }
          refreshList();
        },
        showLoading: false,
        showSuccessMsg: false,
        showFailMsg: false,
      );
    } else {
      communitySearchBean = null;
      refreshList();
    }
  }

  @override
  void dispose() {
    super.dispose();
    easyRefreshController.dispose();
  }
}
